package neu.soft.controller;

import neu.soft.entity.DO.ZipCode;
import neu.soft.entity.Vendor;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.query.VendorPageQuery;
import neu.soft.service.RegionService;
import neu.soft.service.VendorService;
import neu.soft.vo.PageBean;
import neu.soft.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/vendor")
@CrossOrigin
public class VendorController {

    @Autowired
    private VendorService vendorService;

    @Autowired
    private RegionService regionService;

    @PostMapping
    public ResultBean addVendor(@RequestBody Vendor vendor){

        String loc = vendor.getVendorAddress();
        ZipCode zipCode = regionService.find(loc);
        String zip = zipCode.getZipNumber();
        vendor.setZip(zip);
        int res = vendorService.addVendor(vendor);
        if (res < 0){
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
        return ResultBean.success("供应商登记成功");
    }

    @PutMapping
    public ResultBean updateVendor(@RequestBody Vendor vendor){
        int res = vendorService.updateVendor(vendor);
        return ResultBean.success("供应商信息更新成功");
    }

    @DeleteMapping
    public ResultBean deleteVendor(@RequestBody String vendorId){
        if (vendorId==null){
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        int res = vendorService.deleteVendor(Integer.parseInt(vendorId));
        return ResultBean.success("供应商删除成功");
    }

    @PostMapping("/page")
    public ResultBean<PageBean<Vendor>> findByPage(@RequestBody VendorPageQuery vendorQuery) {

        PageBean<Vendor> vendorList = vendorService.findByPage(vendorQuery);
        return ResultBean.success(vendorList);
    }

    @GetMapping
    public ResultBean<List<Vendor>> findAll(){
        return ResultBean.success(vendorService.findAll());
    }

    @PostMapping("/getByName")
    public Vendor getByName(String vendorName){
        return vendorService.findByName(vendorName);
    }

}
